package com.jia.leetCode;

/**
 * 1370. 上升下降字符串
 */
public class Pro1370 {
    public String sortString(String s) {
        int[] cs = new int[26];
        for(int i = 0; i < s.length(); i++) {
            cs[s.charAt(i) - 'a']++;
        }
        boolean isInc = true;
        StringBuilder sb = new StringBuilder();
        while(!isAllZeros(cs)) {
            if(isInc) {
                sb.append(incStr(cs));
                isInc = false;
            }else {
                sb.append(descStr(cs));
                isInc = true;
            }
        }
        return sb.toString();
    }

    private StringBuilder descStr(int[] cs) {
        StringBuilder sb = new StringBuilder();
        for(int i = cs.length - 1; i >= 0; i--) {
            if(cs[i] > 0) {
                sb.append((char)(i + 'a'));
                --cs[i];
            }
        }
        return sb;
    }

    private StringBuilder incStr(int[] cs) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 26; i++) {
            if(cs[i] > 0) {
                sb.append((char)(i + 'a'));
                --cs[i];
            }
        }
        return sb;
    }

    private boolean isAllZeros(int[] cs) {
        for(int i = 0; i < 26; i++) {
            if(cs[i]!=0) {
                return false;
            }
        }
        return true;
    }
}
